package source
{
	import com.justinbuser.net.DynamicURLLoader;
	import com.justinbuser.singleton.Core;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.utils.ObjectUtil;
	
	import spark.core.ContentCache;

	[Event(name="fullReportLoaded", type="flash.events.Event")]
	
	[Bindable] public class BattleReport extends EventDispatcher
	{
		//http://battlelog-cdn.battlefield.com/public/base/bf3/map_images/62x42/mp_011.jpg?v=380 
		public var icon:String;
	/*	public var label:String;*/
		public var gameType:String;
		public var gameMode:int;
		public var mapName:String;
		public var mapId:String;
		public var message:String;
		public var resultScores:String;
		public var won:Boolean;
		public var reportURL:String;
		public var reportId:String;
		public var platform:String;
		public var reportDate:String;
		private var core:Core;
		private var _fullReport:FullBattleReport;
		public var jsonReport:Object;
		public const gameTypes:Object = {1:"Conquest",2:"Rush",4:"Squad Rush",8:"Squad DM",16:"Conquest Assault",32:"Team DM",64:"Conquest Large"};
		public static var mapBGCache:ContentCache;
		
		public function BattleReport(report:Object=null)
		{
			core = Core.core;
			if(!mapBGCache)
			{
				mapBGCache = new ContentCache();
				mapBGCache.enableCaching = true;
				mapBGCache.enableQueueing = true;
				//mapBGCache.maxActiveRequests = 1;
				//mapBGCache.maxCacheEntries = 30;
			}
			if(report)
			{
				try{
					var date:Date = new Date(report.createdAt * 1000);
					var reportDay:String = String(date.date).length == 2 ? String(date.date) : "0"+date.date;
					var reportMonth:String = String(date.month).length == 2 ? String(date.month) : "0"+date.month;
					var reportHours:String = String(date.hours).length == 2 ? String(date.hours) : "0"+date.hours;
					var reportMinutes:String = String(date.minutes).length == 2 ? String(date.minutes) : "0"+date.minutes;
					var reportSeconds:String = String(date.seconds).length == 2 ? String(date.seconds) : "0"+date.seconds;
					reportId = report.reportId;
					platform = report.platform;
					reportDate = reportMonth+"/"+reportDay+"/"+date.fullYear+" at "+reportHours+":"+reportMinutes+":"+reportSeconds;
					won = report.winStatus == 1;
					reportURL = "http://battlelog.battlefield.com/bf3/battlereport/loadgeneralreport/"+reportId+"/"+platform+"/";
					gameMode = report.gameMode;
					gameType = gameTypes[gameMode];
					mapId = String(report.mapName).toLowerCase();
					icon = "http://battlelog-cdn.battlefield.com/public/base/bf3/map_images/992x164/"+mapId+".jpg";
					mapName = core.translations["ID_M_LEVELNAME_"+mapId.toUpperCase()];
					message = report.winStatus == 1 ? "Victorious" : "Defeated";
				}
				catch(e:Error){
					trace("BattleReport Error:",e.getStackTrace(),"\n",JSON.stringify(report));
				}
			}
			
		}
		
		public function getFullReport(responder:Function = null):void{
			core = Core.core;
			var reportIndex:String = reportId+"_"+platform; 
			loadStoredReport();
			
			function pullReport():void{
				var loader:DynamicURLLoader = new DynamicURLLoader(parseFullReport);
				trace('pulling:',reportIndex,reportURL);
				loader.open(reportURL,null,10,"GET");
			}
			
			function parseFullReport(e:Event):void{
				jsonReport = JSON.parse(e.target.data).gameReport;
				if(gameMode == 2 || gameMode == 4){
					if(responder != null)
					{
						responder(fullReport);
					}
					core.reportCache[reportIndex] = jsonReport.valueOf();
					return;
				}
				try{
					var teamScore1:Number = Number(jsonReport.mapModeResult.ticket[1]);
					var teamScore2:Number = Number(jsonReport.mapModeResult.ticket[2]);
					trace(reportIndex, teamScore1,teamScore2);
					core.reportCache[reportIndex] = jsonReport.valueOf();
					var resultDifference:Number = Math.abs(teamScore1 - teamScore2);
					resultScores = won ? "Won by: " : "Lost by: ";
					resultScores += String(resultDifference);
					resultScores += " tickets";
					if(responder != null)
					{
						responder(fullReport);
					}
				}
				catch(error:Error){
					trace(error.getStackTrace());
				}
			}
			
			function loadStoredReport():void{
				if(core.reportCache[reportIndex])
				{
					jsonReport = core.reportCache[reportIndex];
					if(gameMode == 2 || gameMode == 4){
						if(responder != null)
						{
							responder(fullReport);
						}
						return;
					}
					try{
						var resultDifference:Number = Math.abs(Number(jsonReport.mapModeResult.ticket[1]) - Number(jsonReport.mapModeResult.ticket[2]));
						resultScores = won ? "Won by: " : "Lost by: ";
						resultScores += String(resultDifference);
						resultScores += " tickets";
						if(responder != null)
						{
							responder(fullReport);
						}
					}
					catch(error:Error){
						trace(error.getStackTrace());
						pullReport();
					}
				}
				else{
					pullReport();	
				}
			}
		}
		
		[Bindable('fullReportLoaded')]
		public function get fullReport():FullBattleReport{
			if(!_fullReport && jsonReport)
			{
				fullReport = new FullBattleReport(jsonReport,gameType + ": "+mapName);
			}
			return _fullReport;
		}
		
		public function set fullReport(o:FullBattleReport):void{
			_fullReport = o;
			dispatchEvent(new Event('fullReportLoaded'));
		}
	}
}